package com.shujia.dao;

import com.shujia.bean.User;

import java.sql.*;

public class UserDaoImpl implements UserDao {

    private static Connection con;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //建立连接
            con = DriverManager.getConnection("jdbc:mysql://node3:3306/shujia", "root", "123456");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public User queryUserByUsername(String username) {


        User user = null;

        //1、加载驱动
        try {

            // 通过用户名查询用户
            PreparedStatement stat = con.prepareStatement("select username,password from user where username=?");

            stat.setString(1, username);

            ResultSet resultSet = stat.executeQuery();

            //解析数据
            if (resultSet.next()) {
                String username1 = resultSet.getString("username");
                String password = resultSet.getString("password");

                user = new User(username1, password);

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        //返回

        return user;

    }

    @Override
    public void insert(User user) {
        try {
            PreparedStatement stat = con.prepareStatement("insert into user(username,password) values(?,?)");

            stat.setString(1, user.getUsername());
            stat.setString(2, user.getPassword());


            //执行sql
            stat.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void modifyPasswordByUsername(String username, String password) {

    }
}
